// pages/usercenter/pladge/pladge.js
import {
  users
} from '../../../../tools/users'
import {
  ui
} from '../../../../tools/ui'
import {
  pay
} from '../../../../tools/pay'
import {
  checkTool
} from '../../../../tools/check'
import {
  msg
} from '../../../../tools/msg'
import {
  ds
} from '../../../../tools/data'
import {
  dsx
} from '../../../../tools/datax'
import {
  dateTool
} from '../../../../tools/date';
import {
  nav2
} from '../../../../tools/nav2';

Page({
  data: {
    refoundUsers: null,
    deductUsers: null,
  },
  onLoad(options) {
    this.init()
  },
  init() {
    ui.loading()
    this.loadDeductUsers()
  },
  async loadDeductUsers() {
    dsx.getAll('users', {
        bind: dsx.cmd.exists(true)
      }, {
        _id: true,
        _openid: true,
        bind: true
      })
      .then(async res => {
        const counter = {},
          deductUsers = []

        for (const user of res) {
          if (counter[user.bind]) counter[user.bind] = counter[user.bind] + 1
          else counter[user.bind] = 1

          if (counter[user.bind] > 1) continue

          await users.getUserByOpenid(user.bind, {
              _id: true,
              _openid: true,
              personInfo: true,
              shop: {
                name: true
              }
            })
            .then(auser => {
              if (auser) deductUsers.push(auser)
            })
        } // end for
        // count

        for (const user of deductUsers) {
          user.bindCount = counter[user._openid]
        }
        this.setData({
          deductUsers
        })
        ui.loading(false)
      })
  },
  callMobile(e) {
    const mobile = ui.eventData(e, "mobile")
    wx.makePhoneCall({
      phoneNumber: mobile,
    })
  },
  nickNameTap(e) {
    const uid = ui.eventData(e, 'uid')
    nav2.staffEdit('edit', uid)
  },
  onPullDownRefresh() {
    this.init()
  }
})